package com.sun.test22.mapper;

import com.sun.test22.entity.Role;
import com.sun.test22.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM users WHERE id = #{id}")
    User getUserById(int id);

    @Insert("INSERT INTO users(username, email) VALUES(#{username}, #{email})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insertUser(User user);
    @Select("<script>" +
            "SELECT * FROM users " +
            "<where>" +
            "<if test='id != null'>AND id = #{id}</if>" +
            "<if test='username != null'>AND username = #{username}</if>" +
            "<if test='email != null'>AND email = #{email}</if>" +
            "</where>" +
            "</script>")
    List<User> getUsersByCriteria(User criteria);
    @Results(id = "userResultMap", value = {
            @Result(property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "role", column = "role_id",
                    one = @One(select = "getRoleById"))
    })
    @Select("SELECT u.*, r.id as role_id, r.role_name FROM users u LEFT JOIN roles r ON u.role_id = r.id WHERE u.id = #{id}")
    User getUserWithRoleById(int id);

    @Select("SELECT * FROM roles WHERE id = #{id}")
    Role getRoleById(int id);
}
